import React, { Component } from 'react';
import BaseTableComp from '../common/BaseTableComp';
import { WeaTools, WeaLocaleProvider, WeaDialog, WeaAlertPage } from 'ecCom';
import { message } from 'antd';
import { toJS } from 'mobx';
import { observer, inject } from 'mobx-react';
import Forward from '../common/Forward';
import BatchSubmitComp from '../common/BatchSubmitComp';
import SuperviseDialogComp from './SuperviseDialogComp';
import { getDoing, getTodo } from '../../util/getUserName';

const { getLabel } = WeaLocaleProvider;
/*
topTitle WeaTop的title
topBtns  WeaTop的btns

tabKey  选项卡的主键
tabUrl  获取tab数据的接口
tabParams 获取tab数据的参数
searchFormUrl 获取高级搜索的接口
searchParams 获取高级搜索的参数
baseSearchName 基础搜索的name
selectedTabKey 直接设置tab页签的selectedTabKey

tableUrl 获取列表数据的接口
tableParams 获取列表数据的参数
getColumns  需要自定义渲染的方法
onOperatesClick 操作
*/

@inject('customPageStore')
@observer
class CustomTableComp extends Component {
  constructor(props) {
    super(props);
    const { location } = this.props;
    const customListId = location.query.customListId;
    this.state = {
      forwardParams: {},
      showForWard: false,
    };
    this.getTableDatas = this.getTableDatas.bind(this);
    this.getTabData = this.getTabData.bind(this);
    this.getSearchFormItem = this.getSearchFormItem.bind(this);
    this.weaTableProps = {
      rowKey: this.getRowKey,
    };
    this.tabParams = { customListId };
    this.searchParams = { customListId };
    this.searchType = ['base', 'advanced'];
  }

  componentDidMount () {
    window.isOdocOpenWF = true;
    window.getOdocWFList = () => {
      setTimeout(() => {
        this.getTableDatas({}, false, false);
        this.getTabData();
      }, 3000);
    };
    const { customPageStore, location, customTabId = 0 } = this.props;
    const customListId = location.query.customListId || '2';
    customPageStore.setMobxState({ customListId });
    let queryDatas = {};
    if (location.query.conditionKeys) {
      queryDatas[location.query.conditionKeys] = location.query.conditionVals;
    }
    queryDatas = { ...queryDatas, ...location.query };
    customPageStore.getCustomPageListStatus(this.getTableDatas, this.getSearchFormItem, queryDatas, customTabId);
    customPageStore.getBatchLimit();
  }

  componentWillUnmount () {
    const { customPageStore } = this.props;
    window.isOdocOpenWF = null;
    window.getOdocWFList = null;
    customPageStore.initState();
  }

  render () {
    const { customPageStore, location } = this.props;
    const { pageTitle, isOpen, tableParams } = customPageStore;
    const customListId = location.query.customListId;
    const isLibraryId = ['-13', '-17', '-21', '-8'];
    if (isOpen == true) {
      return (
        <BaseTableComp ecId={`${this && this.props && this.props.ecId || ''}_BaseTableComp@6e6b4c`}
          getColumns={this.getColumns}
          topTitle={pageTitle}
          searchType={this.searchType}
          topBtns={this.getTopBtns()}
          tabKey="customTabId"
          selectedTabKey=""
          baseSearchName={isLibraryId.includes(customListId) ? 'odocSubject' : 'requestname'}
          tabUrl="/api/odoc/odocCustomPage/getCustomPageCount"
          searchFormUrl="/api/odoc/odocCustomPage/getCustomPageCondition"
          tableUrl="/api/odoc/odocCustomPage/getCustomPageList"
          ref={refs => this.baseTableComp = refs}
          tabParams={this.tabParams}
          tableParams={tableParams}
          searchParams={this.searchParams}
          showCustomCol={true}
          showExportTable={true}
          moreTimeGetCondition={false}
          onOperatesClick={this.onOperatesClick}
          getOtherDom={this.getOtherDom}
          changeTabFun={this.changeTabFun}
          canGetTableData={false}
          initGetForm={false}
          weaTableProps={this.weaTableProps}
          showSearchGroup
          {...this.props}
        />
      );
    } else if (isOpen == false) {
      return (
        <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@ggfuf4`} icon="icon-coms-locking" >
          <div style={{ color: '#000' }}>
            {getLabel('517287', '此页面没有启用')}
          </div>
        </WeaAlertPage>
      );
    }
  }

  getColumns = (columns) => {
    let newColumns = columns.map((column) => {
      if (column.dataIndex == 'wbr') {
        return {
          ...column,
          render: (text, record) => (
            <div id={`${record.requestid}todo`}>
              <span style={{ cursor: 'pointer', textDecoration: 'underline' }} onClick={() => getTodo(record.requestid, `${record.requestid}todo`)}>{record.wbrspan}</span>
            </div>
          ),
        };
      } else if (column.dataIndex == 'zbr') {
        return {
          ...column,
          render: (text, record) => (
            <div id={`${record.requestid}doing`}>
              <span style={{ cursor: 'pointer', textDecoration: 'underline' }} onClick={() => getDoing(record.requestid, `${record.requestid}doing`)}>{record.zbrspan}</span>
            </div>
          ),
        };
      }
      return column;
    });
    return newColumns;
  }


  onOperatesClick = (record, index, operate) => {
    // 公文流程
    // 跟踪
    if (index == '3') {
      this.onTrack([record.requestid]);
      // 转发
    } else if (index == '1') {
      let params = {
        requestid: record.requestid,
        nodeid: record.nodeid2,
        showForward: true,
        forwardflag: '1',
        forwardOperators: '',
      };
      this.setState({ forwardParams: params, showForWard: true });
      // 打印
    } else if (index == '2') {
      this.doPrintRequest(record.requestid, record.creater);
      // 标记已读
    } else if (index == '0') {
      const needUserId = operate.otherpara.split('+')[1] === 'true';
      this.doReadRequest([record.requestid], needUserId, record.userid);
    }
    // 取消跟踪
    else if (index == '4') {
      this.onCancelTrack([record.requestid]);
    }
    else if(index == '-23'){
        this.onActiveWorkflow([record.requestid]);
    }

    // 公文督办
    const { customPageStore } = this.props;
    const { setMobxState, onSupervise, reminder, checkDetails, cancelReminder, getDelayDateCondtion } = customPageStore;
    setMobxState({
      workflowid: record.workflowid,
      operationType: Number(index) - 5,
      requestid: record.requestid,
      superviseid: record.superviseid,
    });
    const getTableDatas = (this.baseTableComp && this.baseTableComp.wrappedInstance.getTableDatas) || null;
    const getTabData = (this.baseTableComp && this.baseTableComp.wrappedInstance.getTabData) || null;
    // 5督办 6催办 7查看督办详情（督办详情） 8 取消督办 9查看督办详情（被督办者）10延期处理申请
    if (index == 5) {
      onSupervise();
    } else if (index == 6) {
      reminder();
    } else if (index == 7) {
      checkDetails();
    } else if (index == 8) {
      cancelReminder(getTableDatas, getTabData);
    } else if (index == 9) {
      checkDetails();
    } else if (index == 10) {
      getDelayDateCondtion();
    }

    // 流程跟踪
    const { processOpinion } = customPageStore;
    // 取消跟踪
    if (index == '4') {
      const requestid = [record.requestid];
      this.onCancelTrack(requestid);
    } else if (index == '11') {
      // 处理意见
      const requestid = [record.requestid];
      const workflowid = record.workflowid;
      processOpinion(requestid, workflowid);
    }
  }

  doPrintRequest = (requestid, beluserid, otherpara = '') => {
    const printurl = '/workflow/request/PrintRequestForward.jsp?';
    const urlParams = `requestid=${requestid}&f_weaver_belongto_userid=${beluserid}&f_weaver_belongto_usertype=0${otherpara}`;
    this.openFullWindowHaveBar(printurl + urlParams);
  }

  openFullWindowHaveBar (url) {
    const width = screen.availWidth - 10;
    const height = screen.availHeight - 50;
    let szFeatures = 'top=0,left=0,';
    szFeatures += `width=${width},`;
    szFeatures += `height=${height},`;
    szFeatures += 'directories=no,status=yes,toolbar=no,location=no,';
    szFeatures += 'menubar=no,scrollbars=yes,resizable=yes';
    window.open(url, '', szFeatures);
  }

  doReadRequest (requestids, needUserId, userId) {
    let params = {
      opertype: requestids.length > 1 ? 'batch' : 'single',
      requestid: requestids.join(','),
    };
    if (needUserId) {
      params = {
        ...params,
        f_weaver_belongto_userid: userId,
        f_weaver_belongto_usertype: 0,
      }
    }
    WeaTools.callApi('/api/workflow/reqlist/doReadIt', 'POST', params).then((data) => {
      if (data.api_status) {
        this.getTableDatas({}, false, false);
        message.success(getLabel('517288', '已读成功'));
      }
    });
  }

  onCancelTrack (keys, clear) {
    const params = {
      requestid: keys.join(','),
    };
    WeaTools.callApi('/api/odoc/odocNewTodoList/removeTracksReq', 'POST', params).then((data) => {
      if (data.api_status) {
        message.success(getLabel('129248', '取消成功'));
        clear && clear();
        this.getTabData();
        this.getTableDatas({}, false, false);
      }
    });
  }

  onTrack (selectedKeys, clear) {
    const params = {
      requestid: selectedKeys.join(','),
    };
    WeaTools.callApi('/api/odoc/odocNewTodoList/addTracksReq', 'POST', params).then((data) => {
      if (data.api_status) {
        message.success(getLabel('517285', '跟踪成功'));
        clear && clear();
        this.getTabData();
        this.getTableDatas({}, false, false);
      }
    });
  }

  getOtherDom = () => {
    const { forwardParams, showForWard } = this.state;
    const { customPageStore } = this.props;
    const { processOpinionHide, processOpinionVisible, showBatchSubmit, setMobxState, batchSubmitEvent } = customPageStore;
    // const getTableDatas = (this.baseTableComp && this.baseTableComp.wrappedInstance.getTableDatas) || null;
    // const getTabData = (this.baseTableComp && this.baseTableComp.wrappedInstance.getTabData) || null;
    return (
      <div>
        {
          showForWard &&
          <Forward ecId={`${this && this.props && this.props.ecId || ''}_Forward@v0ocl8`} forwardParams={forwardParams} callBackActions={null} />
        }

        <BatchSubmitComp ecId={`${this && this.props && this.props.ecId || ''}_BatchSubmitComp@jvkzey`}
          visible={showBatchSubmit}
          onSubmit={remark => batchSubmitEvent(remark, this.getTableDatas, this.getTabData)}
          onCancel={() => setMobxState({ showBatchSubmit: false })}
        />

        <SuperviseDialogComp
          ecId={`${this && this.props && this.props.ecId || ''}_SuperviseDialogComp@46yc8n`}
          getTableDatas={this.getTableDatas}
          getTabData={this.getTabData}
        />

        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@m9dqfr`}
          title={getLabel('125734', '流转意见')}
          icon="icon-coms-official"
          iconBgcolor="#f14a2d"
          onCancel={processOpinionHide}
          visible={processOpinionVisible}
          style={{ width: 600, height: 600 }}
          hasScroll
        >
          {this.getDiaglogContent()}
        </WeaDialog>
      </div>
    );
  }

  getDiaglogContent () {
    const { customPageStore } = this.props;
    const { opinionList } = customPageStore;
    if (toJS(opinionList).length == 0) {
      return (
        <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@x1ebj8`} icon="icon-coms-blank" >
          <div style={{ color: '#000' }}>
            {getLabel(83553, '暂无数据')}
          </div>
        </WeaAlertPage>
      );
    }
    return (
      <div className="WFTrackDialog">
        {
          toJS(opinionList).map(item => (
            <div className="wf-req-sign-list-content">
              <div className="content-left" style={{ paddingLeft: '48px' }}>
                <img src={item.img_path} className="content-text-left-user-img" />
                <div style={{ width: '132px' }}>
                  <p><a href={`javaScript:openhrm(${item.displayid})`} onClick={e => pointerXY(e)}>{item.displayname}</a></p>
                  <span >
                    <a href="/spa/hrm/engine.html#/hrmengine/organization?showTree=false&amp;isView=1&amp;type=department&amp;id=&amp;_key=3b4uab"
                      target="_blank"
                      style={{ color: 'rgb(155, 155, 155)', whiteSpace: 'pre-wrap' }}
                    /></span>
                </div>
              </div>
              <div className="content-right">
                <div className="content-right-remark-html">
                  <p dangerouslySetInnerHTML={{ __html: item.log_remarkHtml }} />
                </div>
                <p style={{ lineHeight: '24px', color: 'rgb(138, 138, 138)' }}>
                  <span className="receiveUserLable">{getLabel('15525', '接收人')} : </span>
                  <span title={item.receiveUser} className="receiveUser">{item.receiveUser}</span>
                </p>
                <p style={{ lineHeight: '22px', marginTop: '10px', color: 'rgb(154, 154, 154)' }}><span
                  style={{ marginRight: '8px' }}
                >{item.log_operatedate}&emsp;{item.log_operatetime} </span><span>[{item.log_nodename} / {item.operationname}]</span></p>
              </div>
            </div>
          ))
        }
      </div>
    );
  }

  getTopBtns () {
    const { customPageStore } = this.props;
    const { getButtonType, sharearg, buttonType } = customPageStore;
    let datas = [];
    if (getButtonType.includes('-23')) {
      datas.push(
        { key: '-23', show: getLabel('533270', '激活'), icon: <i className="icon-portal-operation" /> },
      );
    }else{
      if (getButtonType.includes('1')) {
        if (sharearg.hasBatchReadBtn === 'true') {
          datas.push(
            { key: '1', show: getLabel('17598', '批量提交'), icon: <i className="icon-coms-Approval-o" /> },
          );
        }
      }
      if (getButtonType.includes('2')) {
        if (sharearg.hasBatchSubmitBtn === 'true') {
          datas.push(
            { key: '2', show: getLabel('517765', '批量已读'), icon: <i className="icon-coms--postil" /> },
          );
        }
      }
      if (getButtonType.includes('3')) {
        datas.push(
          { key: '3', show: getLabel('513369', '批量跟踪'), icon: <i className="icon-portal-operation" /> },
        );
      }
      if (getButtonType.includes('4')) {
        datas.push(
          { key: '4', show: getLabel('517318', '批量取消跟踪'), icon: <i className="icon-portal-operation" /> },
        );
      }    
    }
   
    
    let buttons = [];
    if (datas.length > 1) {
      buttons = [
        {
          isDropDown: true,
          needCheck: true,
          datas,
          btnOnClick: (key, selectedKeys, selectedDatas, clear) => this.topBtnOnClick(key, selectedKeys, selectedDatas, clear),
          menuOnClick: key => this.menuOnClick(key),
          buttonKey: buttonType,
        },
      ];
    } else if (datas.length == 1) {
      datas[0].title = datas[0].show;
      datas[0].needCheck = true;
      datas[0].onClick = (selectedKeys, selectedDatas, clear) => this.topBtnOnClick(datas[0].key, selectedKeys, selectedDatas, clear);
      buttons = datas;
    }
    return buttons;
  }

  // 重新获取列表
  getTableDatas (params = {}, onlyParams, covered, saveParams) {
    this.baseTableComp && this.baseTableComp.wrappedInstance.getTableDatasByDirect(params, onlyParams, covered, saveParams);
  }

  // 重新获取页签
  getTabData () {
    this.baseTableComp && this.baseTableComp.wrappedInstance.getTabData();
  }

  // 重置高级搜索
  resetForm () {
    this.baseTableComp && this.baseTableComp.wrappedInstance.resetForm();
  }

  // 获取高级搜索
  getSearchFormItem (params) {
    return this.baseTableComp.wrappedInstance.getSearchFormItem(params);
  }

  topBtnOnClick (key, selectedKeys, selectedDatas, clear) {
    // 批量已阅
    const { customPageStore } = this.props;
    const { setMobxState, secondAuth, sharearg } = customPageStore;
    const datas = selectedKeys.map(item => item.split('_')[0]);
    if (key == '1') {
      // 弹窗输入签字意见
      setMobxState({ selectedKeys: datas, selectedDatas });
      if (sharearg.multisubmitnotinputsign == '1') {
        setMobxState({ showBatchSubmit: true });
      } else {
        secondAuth('', this.getTableDatas, this.getTabData);
      }
    }
    // 批量提交
    if (key == '2') {
      this.batchReadRequest(datas);
    }
    if (key == '3') {
      this.onTrack(datas, clear);
    }
    if (key == '4') {
      this.onCancelTrack(datas, clear);
    }
    //流程激活
    if(key=='-23') 
    {
       this.onActiveWorkflow(datas);
    }
  }


  onActiveWorkflow (keys) {
    const params = {
      requestid: keys.join(','),
    };
    WeaTools.callApi('/api/workflow/gwforward/doActiveWorkflow', 'POST', params).then((data) => {
      if (data.api_status) {
        message.success(getLabel('385622', '激活成功'));
        this.getTabData();
        this.getTableDatas({}, false, false);
      }
    });
  }

  menuOnClick (key) {
    const { customPageStore } = this.props;
    const { setMobxState } = customPageStore;
    setMobxState({ buttonType: key, selectedKeys: [], selectedDatas: [] });
    this.getTableDatas({ btnType: key }, false, false);
  }

  changeTabFun = (tabId) => {
    const { customPageStore } = this.props;
    const { getTopButton } = customPageStore;
    this.resetForm();
    getTopButton(tabId, {}, this.getTableDatas, this.getSearchFormItem);
  }

  getRowKey = record => `${record.randomFieldId}_${record.userid || ''}`;
  batchReadRequest = (datas) => { 
    const params = {
      action: "batchRead",
      requestId: datas.join(',')
    }
    WeaTools.callApi('/api/odoc/odocCustomPage/doCustomPageAction', 'POST', params).then((data) => {
      if (data.api_status) {
        this.getTableDatas({}, false, false);
        message.success(getLabel('517288', '已读成功'));
      }
    });
  }
}

export default props => <CustomTableComp ecId={`${this && this.props && this.props.ecId || ''}_CustomTableComp@hz40yz`} {...props} key={props.location.query.customListId || '-1'} />;
